<?php

namespace app\common\model\system;

use app\common\model\BaseModel;
use think\Exception;

/**
 * 地区表
 * Class SystemArea
 * @package app\common\model\system
 */
class SystemAreaModel extends BaseModel
{
    //
    protected $name = 'system_area';

    // 设置字段信息
    protected $schema = [
        'id' => 'int',        // 地区ID
        'title' => 'string',        // 地区名称
        'pid' => 'int',        // 父ID
        'path' => 'string',        // 路径
        'depth' => 'int',        // 深度
        'child' => 'int',        // 子节点数
        'sort' => 'int',        // 排序
        'area_code' => 'string',        // 行政码
    ];


    /**
     * 地区列表
     * @param int $id 要获取的父级ID
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function areaList(int $id): array
    {
        $where = [];
        if ($id < 1) {
            $where[] = ['pid', '=', 0];
        } else {
            $where[] = ['pid', '=', $id];
        }

        return $this->field('id,title,area_code')->where($where)->order('sort desc')->select();
    }

    //

    /**
     * 地址解析
     * @param string $county_code 地址编号
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function areaInfo(string $county_code): array
    {
        if (empty($county_code)) {
            return [];
        }
        $province_code = str_pad(substr($county_code, 0, 2), 6, '0');
        $city_code = str_pad(substr($county_code, 0, 4), 6, '0');

        $arealist = $this->db()
            ->where('area_code', 'in', [$province_code, $city_code, $county_code])
            ->column('id,title,area_code', 'area_code');


        return [
            'province_id' => $arealist[$province_code]["id"] ?? 0,
            'province' => $arealist[$province_code]["title"] ?? '',
            'province_code' => $arealist[$province_code]['area_code'] ?? '',
            'city_id' => $arealist[$city_code]['id'] ?? 0,
            'city' => $arealist[$city_code]['title'] ?? '',
            'city_code' => $arealist[$city_code]['area_code'] ?? '',
            'county_id' => $arealist[$county_code]['id'] ?? 0,
            'county' => $arealist[$county_code]['title'] ?? '',
            'county_code' => $arealist[$county_code]['area_code'] ?? '',
        ];
    }

    /**
     * 根据省市区转换为areacode
     * @param $provinceCode string 省份code
     * @param $cityCode string 城市code
     * @param $countyCode string 县区code
     * @return string
     */
    public function deAreaInfo($provinceCode, $cityCode, $countyCode)
    {
        return mb_substr($provinceCode, 0, 2) . mb_substr($cityCode, 2, 2) . mb_substr($countyCode, 4, 2);
    }

}
